import { ref, Ref } from 'vue';
import { codeGenInner, codeGenZip, codePreview } from '/@/api/gen/codegen';
import {
  CodeGenConfigParams,
  GenCodePreviewModel,
  TableFieldConfig,
} from '/@/api/gen/model/CodeGenModel';

export function useCodeGen(option: { genConfig: Ref<CodeGenConfigParams | undefined> }) {
  const previewCodes = ref({} as GenCodePreviewModel);
  function downloadZip(genConfig = option.genConfig) {
    return codeGenZip(genConfig.value).then((res) => {
      if (res.status == 200) {
        const blob = new Blob([res.data], { type: 'application/zip' }); //处理文档流
        const fileName = genConfig.value!.genBaseConfigEntity.zipName + '.zip';
        const down = document.createElement('a');
        down.download = fileName;
        down.style.display = 'none'; //隐藏,没必要展示出来
        down.href = URL.createObjectURL(blob);
        document.body.appendChild(down);
        down.click();
        URL.revokeObjectURL(down.href); // 释放URL 对象
        document.body.removeChild(down); //下载完成移除
        return true;
      }
    });
  }

  function previewCode(genConfig = option.genConfig) {
    return codePreview(genConfig.value).then((res) => {
      previewCodes.value = res;
      return res;
    });
  }

  function genCodeInner(genConfig = option.genConfig) {
    return codeGenInner(genConfig.value);
  }

  return {
    downloadZip,
    genCodeInner,
    previewCode,
    previewCodes,
  };
}

export const defaultCodeGenConfig = {
  genBaseConfigEntity: {
    afterEndParentPath: 'agilefast-platform/agilefast-gen-api/src/main',
    apiPrefix: '/v2/api',
    author: 'yaolonga',
    frontEndParentPath: 'J:\\',
    sqlParentPath: 'J:\\',
    otherParentPath: 'J:\\',
    genMode: 'inner',
    moduleName: 'test',
    moduleNameZh: '测试模块',
    zipName: '微标基础框架3',
    outputType: 'file',
    packageName: 'io.agilefast.modules',
    removeTablePrefix: false,
    tablePrefixName: '',
    templateGroupId: 1,
    version: 'v1.2.0',
    idType: 'AUTO',
  },
  genDataSourceEntity: {
    dbAlias: 'local-mysql-agilefastfk',
    dbDriver: 'com.mysql.jdbc.Driver',
    dbName: 'gen',
    dbPassword: 'yin7372175240000',
    dbType: 'mysql',
    dbUrl:
      'jdbc:mysql://localhost:3306/gen?allowMultiQueries=true&useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true',
    dbUserName: 'root',
    dbinfoId: 0,
  },
  genTableConfigs: [
    {
      businessName: '',
      javaBeanName: '',
      listConfigEntity: {
        isBatch: true,
        isPage: true,
        showAddBtn: true,
        showDelBtn: true,
        showExportBtn: true,
        showImportBtn: true,
        showUpdateBtn: true,
        existSearchField: false,
        updateOrCreateEditComponent: 'Modal',
        pid: 0,
        sort: 10,
      },
      tableComment: '',
      tableFieldConfig: [
        {
          comment: '',
          componentType: '',
          dictType: '',
          field: '',
          fieldDict: [],
          isDisableField: true,
          isGenColumn: true,
          isGenFieldByUpdateOrCreate: true,
          isQuery: true,
          isShowFieldByUpdateOrCreate: true,
          javaType: '',
          queryModeSelect: 0,
          required: true,
          showTableColumn: true,
          tsType: '',
          type: '',
        },
      ],
      tableName: 'gen_global_params',
    },
  ],
  pid: 0,
  sort: 10,
};

//转换成table数据
export function transferTableData(fields: Array<any>): TableFieldConfig[] {
  const java2TsMapTable = new Map();
  java2TsMapTable.set('String', 'string');
  java2TsMapTable.set('Integer', 'number');
  java2TsMapTable.set('int', 'number');
  java2TsMapTable.set('Long', 'number');
  java2TsMapTable.set('Boolean', 'boolean');
  java2TsMapTable.set('boolean', 'boolean');
  java2TsMapTable.set('BigInteger', 'number');
  java2TsMapTable.set('BigDecimal', 'number');
  java2TsMapTable.set('double', 'number');
  java2TsMapTable.set('Double', 'number');
  java2TsMapTable.set('Short', 'number');
  java2TsMapTable.set('short', 'number');
  java2TsMapTable.set('float', 'number');
  java2TsMapTable.set('Float', 'number');
  java2TsMapTable.set('char', 'string');
  java2TsMapTable.set('Character', 'string');
  java2TsMapTable.set('Date', 'string');
  java2TsMapTable.set('Time', 'string');
  java2TsMapTable.set('Timestamp', 'string');
  java2TsMapTable.set('DateTime', 'string');
  java2TsMapTable.set('LocalDateTime', 'string');

  function javaTypeToTsType(javaType: string) {
    let tsType = java2TsMapTable.get(javaType);
    if (!tsType) {
      tsType = 'any';
    }
    return tsType;
  }

  return fields.map((field) => {
    const config: TableFieldConfig = {
      comment: field.comment,
      componentType: 'Input',
      dictType: 'none',
      field: field.name,
      fieldDict: [],
      isDisableField: false,
      isGenColumn: true,
      isGenFieldByUpdateOrCreate: field.isCommon ? field.keyFlag || false : true,
      isQuery: false,
      isShowFieldByUpdateOrCreate: field.isCommon ? false : !field.keyFlag,
      javaType: field.propertyType,
      queryModeSelect: 'none',
      required: !field.metaInfo.nullable,
      showTableColumn: true,
      tsType: javaTypeToTsType(field.propertyType),
      type: field.type,
      propertyName: field.propertyName,
      keyIdentityFlag: field.keyIdentityFlag,
      keyFlag: field.keyFlag,
      checkRule: '',
      isCommon: field.isCommon || false,
    };
    return config;
  });
}

//获取主键信息
export function getKeyIdentityInfo(fields: Array<any>) {
  const field = fields.find((field) => field.keyFlag);
  if (field) {
    return {
      keyFlag: field.keyFlag,
      keyName: field.propertyName,
    };
  }
  return { keyFlag: false, keyName: '' };
}
